let col = "vf_trade_info"; //下单表

// let col_02 = "vf_trade_info"; //交易表

const mongoServer = {
  /**
   * @description: 添加订单
   *  @param openId 必填
   *  @param itemId 必填 前端传值必填
   *  @param  orderStatus 默认值
   * @return  order_id  返回订单id
   */
  addOrderInfo: async (ctx, obj) => {
    try {
      let date = curentTime();
      let sqlData = {
        gmt_create: date,
        gmt_modified: date,
        ...obj,
        orderStatus: 0
      };
      let resData = await ctx.mfutil.db.mongo.insertOne(col, sqlData);
      return {
        success: true,
        data: resData,
        errorCode: "",
        errorMessage: ""
      }
    } catch (error) {
      return {
        success: false,
        data: {},
        errorCode: "7000",
        errorMessage: JSON.stringify(error)
      }
    }

  },

  /**
   * @description: 查询订单信息
   * @param  orderId 订单id 必填
   * @return 订单信息
   */
  getOrderInfo: async (ctx, obj) => {
    try {
      let resData = await ctx.mfutil.db.mongo.find(col, obj);
      return {
        success: true,
        data: resData,
        errorCode: "",
        errorMessage: ""
      }

    } catch (error) {
      return {
        success: false,
        data: {},
        errorCode: "7000",
        errorMessage: JSON.stringify(error)
      }
    }
  },



  /**
 * @description: 定时任务 修改订单信息，即已经生成一个订单 ，多久一次？  测试为1分钟，使用待定
 * 步骤：
 * 1.根据openid拉取用户订单数据，更新订单表
 * 问题：
 * 1)返回了该用户的全部订单信息，如何确定就是那个用户的那条订单
 * 解决：遍历交易记录，返回值中有itemid
 *       遍历itemid对应的交易记录，调用taobao.open.trade.get获取交易详情
 *       拿到定制详情中的order_id去查询订单表中的记录，如果找到，就修改该条order_id记录的订单状态和新增tid字段
 * 2)订单数据中如果有tid，就根据tid直接拉取订单的交易状态
 * 3)如何查询订单中的openid？
 *   查询更新时间再一分钟之前的数据，取时间最久的
 * 
 * 4)交易数据中的定制字段必须传入orderId,以便于和订单表中的信息得到匹配，
 */
  updateOrderInfo: async (ctx) => {
    try {
      let arr = await getOrderInfoByTime(ctx);
      let msg;
      if (arr.length) {
        let orderItem = arr[0];
        if (orderItem && orderItem.openId && orderItem.itemId && orderItem._id) {
          let resData = null;
          if (orderItem.tid) {
            resData = await getOrderDetialByTid(ctx, orderItem);
          } else {
            resData = await makeSureOrderId(ctx, orderItem);
          }
          if(resData != 1){
             msg = `未找到订单${orderItem._id}的交易数据，可能是该订单还未生成交易记录`;
            // 修改更新时间
            await updateOrderTime(ctx,orderItem._id)
          }else {
             msg = `修改了订单为${orderItem._id}的订单信息`
          }
        }
      }else {
         msg = "暂时没有要修改的数据了";
      }

      return {
            success: true,
            data: msg,
            errorCode: "",
            errorMessage: ""
      }
    } catch (error) {
      return {
        success: false,
        data: {},
        errorCode: "7000",
        errorMessage: JSON.stringify(error)
      }
    }
  },

}


// ==========调淘宝接口====================//
//处理如果返回的交易数量大于100条
let getAllTradeInfo = async (ctx, openId) => {
  try {
    let obj = await getTrade(ctx, '', openId);
    if (obj.total_results < 100) {
      return obj;
    } else {
      let obj_02;
      let total = Math.ceil(obj.total_results / 100);
      for (let i = 2; i <= total; i++) {
        obj_02 = await getTrade(ctx, i, openId);
        let item = obj_02.trades.trade;
        obj.trades.trade.push(...item);
      }
      return obj;
    }
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: JSON.stringify(error)
    }
  }
}

//拉取买家交易信息
let getTrade = async (ctx, page_no = 1, openId) => {
  const { cloud } = ctx;
  try {
    let result = await cloud.topApi.invoke({
      api: 'taobao.open.trades.sold.get',
      autoSession: true,
      data: {
        'fields': 'tid,type,status,payment,orders,rx_audit_status,buyer_nick',
        buyer_open_id: openId,
        page_no,
        page_size: 100,
      }
    });
    return result;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: JSON.stringify(error)
    }
  }
}

//拉取买家单笔交易信息
let getTradeByTid = async (ctx, tid) => {
  const { cloud } = ctx;
  try {
    const result = await cloud.topApi.invoke({
      api: 'taobao.open.trade.get',
      autoSession: true,
      data: {
        fields: 'tid,type,status,payment,orders,buyer_nick',
        tid,
      }
    });
    return result;
  } catch (error) {
    //必须使用主订单id查询
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: JSON.stringify(error)
    }
  }
}



// ============================关于订单表的操作=============================//
// 查询更新时间小于1分钟之前的数据，取最时间久的，仅查一条
let getOrderInfoByTime = async (ctx) => {
  // return ctx;
  try {
    let time = new Date().getTime() - 1 * 60 * 1000;
    let resData = ctx.mfutil.db.mongo.find(
      col,
      {
        orderStatus: { $nin: ['TRADE_FINISHED', 'TRADE_CLOSED', 'TRADE_CLOSED_BY_TAOBAO'] },
        gmt_modified: { $lte: curentTime(time) }
      },
      { gmt_modified: 1 },
      0,
      1
    );
    return resData;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: '查询订单失败' + JSON.stringify(error)
    }
  }
}

// 根据tid拿到交易详情信息，并更新订单详情
let getOrderDetialByTid = async (ctx, orderItem) => {
  try {
    const {tid,_id} = orderItem;
    const tradeDetial = await getTradeByTid(ctx, tid);
    let obj = null;
    for (let i = 0; i < tradeDetial.trade.orders.order.length; i++) {
      obj = ctx.mfutil.db.mongo.updateMany(col, { _id }, {
        $set: {
          orderStatus: tradeDetial.trade.orders.order[i].status,
          gmt_modified: curentTime()
        }
      })
    }
    return obj;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: '根据Tid查询订单失败' + JSON.stringify(error)
    }
  }
}

// 确定一条订单，并更新订单详情
let makeSureOrderId = async (ctx, orderItem) => {
  try {
    const { openId, itemId, _id } = orderItem;
    let tradeInfo = await getAllTradeInfo(ctx, openId);
    let updateObj = {};
    // 遍历交易列表，根据item，openid，定制详情中的pic下的order_id 确定唯一一条订单，修改订单信息
    for (let i = 0; i < tradeInfo.trades.trade.length; i++) {
      // 根据遍历的tid，获取交易详情
      const tradeDetails = await getTradeByTid(ctx, tradeInfo.trades.trade[i].tid);
      for (let j = 0; j < tradeDetails.trade.orders.order.length; j++) {
        //解析定制字段
        let customization = JSON.parse(tradeDetails.trade.orders.order[j].customization);
        // 根据openId，itemid，_id 确定为当前正在修改的订单。
        if (tradeDetails.trade.orders.order[j].num_iid == itemId && tradeInfo.trades.trade[i].buyer_open_uid == openId && customization.pic[0].id == _id) {
          updateObj = ctx.mfutil.db.mongo.updateMany(col, { _id }, {
            $set: {
              orderStatus: tradeDetails.trade.orders.order[j].status,
              tid: tradeInfo.trades.trade[i].tid,
              customization: tradeDetails.trade.orders.order[j].customization,
              gmt_modified: curentTime()
            }
          })
        }
      }
    }
    return updateObj;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: '订单_id获取失败' + JSON.stringify(error)
    }
  }
}

// 只要遍历到一条订单，就修改订单的更新时间
let updateOrderTime = async (ctx,_id) =>{
  try {
    let res  = ctx.mfutil.db.mongo.updateMany(col, { _id }, {
      $set: {
        gmt_modified: curentTime()
      }
    })
    return res;
  } catch (error) {
    return {
      success: false,
      data: {},
      errorCode: "5000",
      errorMessage: '更新时间修改失败' + JSON.stringify(error)
    }
  }
}

// =====================时间工具===========================//
var curentTime = function (time) {
  var d = time ? new Date(time) : new Date();
  var localTime = d.getTime();
  var localOffset = d.getTimezoneOffset() * 60000; //获得当地时间偏移的毫秒数
  var utc = localTime + localOffset + 3600000 * 8;
  var now = new Date(utc);

  var year = now.getFullYear(); //年
  var month = now.getMonth() + 1; //月
  var day = now.getDate(); //日
  var hh = now.getHours(); //时
  var mm = now.getMinutes(); //分
  var ss = now.getSeconds(); //秒

  var clock = year + "-";

  if (month < 10)
    clock += "0";

  clock += month + "-";

  if (day < 10)
    clock += "0";

  clock += day + " ";

  if (hh < 10)
    clock += "0";

  clock += hh + ":";

  if (mm < 10)
    clock += "0";

  clock += mm + ":";

  if (ss < 10)
    clock += "0";

  clock += ss;

  return (clock);
}

exports.mongoServer = mongoServer;
